//
//  JXCountDownView.swift
//  GodoxFlash
//
//  Created by godox on 2021/12/1.
//

import UIKit

public final class JXCountDownView: UIControl {
    
    /// 点击获取验证码
    public var getCodeDown: (() -> Void)?
    
    private var defaultTotal: Int = 10
    /// 倒计时总时长
    private var countDownTotal: Int = 10
    /// 倒计时label
    private let countDownLabel = UILabel()
    /// 当前系统绝对时间,进入后台后,仍持续计时
    private var startTime: Int = 0
    /// 定时器对象
    private var taskTimer: DispatchSourceTimer?
    
    private var titleCodeT: String = "获取验证码"
    
    private var refeshCodeT: String = "重新获取"
    
    private var secondsT: String = "秒后重试"
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 反初始化器
    deinit { print("JXCountDownView deinit~") }
    
    // MARK: - 初始化器
    public init(timeTotal: Int, titleCodeT: String, refeshCodeT: String, secondsT: String) {
        super.init(frame: .zero)
        self.defaultTotal = timeTotal
        self.countDownTotal = timeTotal
        self.titleCodeT = titleCodeT
        self.refeshCodeT = refeshCodeT
        self.secondsT = secondsT
        self.setUI()
    }
    
    // MARK: - UI初始化
    private func setUI() {
        countDownLabel.text = titleCodeT
        countDownLabel.textColor = UIColor.jx.hexString("#418AFC")
        countDownLabel.font = UIFont.systemFont(ofSize: 14)
        countDownLabel.textAlignment = .center
        addTarget(self, action: #selector(countDownDidSeleted), for: .touchUpInside)
        addSubview(countDownLabel)

    }
    
    public override func layoutSubviews() {
        countDownLabel.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
    }
    
    // MARK: - 验证码发送成功开始倒计时操作
    public func startCountDown() {
        resetData()
        taskTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue(label: "count_down_queue"))
        taskTimer?.schedule(deadline: .now(), repeating: .seconds(1), leeway: .seconds(0))
        taskTimer?.setEventHandler { self.updateData() }
        taskTimer?.resume()
    }
    
    
    // MARK: - 重置数据
    private func resetData() {
        countDownTotal = defaultTotal
        isUserInteractionEnabled = false
        startTime = Int(CACurrentMediaTime())
    }
    
    // MARK: - 更新UI
    private func updateData() {
        // 获取剩余总时长
        self.countDownTotal = self.remainingTime()
        // 主线程刷新UI
        DispatchQueue.main.async { [self] in
            if self.countDownTotal > 0 {
                self.countDownLabel.text = "\(self.countDownTotal)\(self.secondsT)"
            }else {
                self.taskTimer?.cancel()
                self.countDownLabel.text = self.refeshCodeT
                self.isUserInteractionEnabled = true
            }
        }
    }
    
    // MARK: - 点击获取验证码请求
    @objc private func countDownDidSeleted() {
        getCodeDown!()
    }
    
    // MARK: - 获取剩余总时长
    private func remainingTime() -> Int {
        defaultTotal - (Int(CACurrentMediaTime()) - startTime)
    }
}
